import maya.api.OpenMaya as om
def get_uvset_uvs(obj_name, uvset_name):
    sel_list = om.MSelectionList()
    sel_list.add(obj_name)
    
    #m_obj = om.MObject()
    m_obj = sel_list.getDependNode(0)
    print '==========='

    uv_list = []
    face_vtx_iter = om.MItMeshFaceVertex(m_obj)
    
    mesh_fn = om.MFnMesh(m_obj)
    

    
    
    while not face_vtx_iter.isDone():
        if not face_vtx_iter.hasUVs(uvset_name):
            face_vtx_iter.next()
            continue
        face_id = face_vtx_iter.faceId()
        vtx_id = face_vtx_iter.vertexId()
        face_vtx_id = face_vtx_iter.faceVertexId()
        uv_id = face_vtx_iter.getUVIndex(uvset_name)
        uv = face_vtx_iter.getUV(uvset_name)
        print mesh_fn
        print face_id
        vtx_count = mesh_fn.polygonVertexCount(face_id)
        print '--------------'
        
        uv_list.append([face_id, vtx_id, face_vtx_id, uv_id, uv, vtx_count])
        
        face_vtx_iter.next()
        
    return uv_list
    
def reload_uv(obj_name, uvset_name, uv_list):
    sel_list = om.MSelectionList()
    sel_list.add(obj_name)
    dag_path = sel_list.getDependNode(0)
    mesh_fn = om.MFnMesh(dag_path)
    
    all_uvsets_list = cmds.polyUVSet(obj_name, q=1, allUVSets=True)
    if uvset_name in all_uvsets_list:
        mesh_fn.clearUVs(uvset_name)
    else:
        mesh_fn.createUVSet(uvset_name)
        
    u_list = []
    v_list =[]
    uv_id_list = []
    uv_count_dict = {}
    
    for uv_data in uv_list:
        uv = uv_data[4]
        u_list.append(uv[0])
        v_list.append(uv[1])
        uv_id_list.append(uv_data[3])
        face_id = uv_data[0]
        uv_count_dict[face_id] = uv_data[5]
    
    uv_counts = [uv_count_dict[i] for i in sorted(uv_count_dict.keys())]
    mesh_fn.setSomeUVs(uv_id_list, u_list, v_list, uvset_name)
    mesh_fn.assignUVs(uv_counts, uv_id_list, uvset_name)
    
def uv_file_node_link(obj_name, file_node, uvset_name):
    uvset_indics = cmds.polyUVSet(obj_name, q=1, allUVSetsIndices=True)
    for i in uvset_indics:
        name = cmds.getAttr(obj_name+".uvSet["+ str(i) +"].uvSetName")
        if name == uvset_name:
            cmds.uvLink("pPlane1.uvSet["+ str(i) +"].uvSetName", file_node)
            
uv_list = get_uvset_uvs('pPlaneShape1', 'uvSet')

reload_uv('pPlaneShape1', 'map1', uv_list)
        

    
    
    
    